﻿using Google.Protobuf;
using MP_Game.Protos.V1;
using System;

namespace MP_Network.Ctrls
{
    internal class HealthCtrl : IContainer
    {
        public void OnServerCommand(ServerBase serverBase, GamePacket packet)
        {
            if (packet.CmdId == CmdId.CmdPingReq)
            {
                PingReq req = PingReq.Parser.ParseFrom(packet.Data);
                if (req != null)
                {
                    if (serverBase != null && serverBase is Session)
                    {
                        Session session = (Session)serverBase;
                        GamePacket rsp = new GamePacket
                        {
                            CmdId = CmdId.CmdPongRsp,
                            SessionId = packet.SessionId,
                            Data = new PongRsp
                            {
                                ClientTime = req.ClientTime,
                                ServerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                            }.ToByteString()
                        };
                        session.Send(rsp);
                        LogMsg.Info(req.ToString());
                    }
                }
            }
        }
        public void OnClientCommand(ServerBase serverBase, GamePacket packet)
        {
            if (packet.CmdId == CmdId.CmdPongRsp)
            {
                PongRsp rsp = PongRsp.Parser.ParseFrom(packet.Data);
                if (rsp != null)
                {
                    long nowLocal = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    // 网络单程延迟
                    long halfRtt = (nowLocal - rsp.ClientTime) >> 1;

                    long serverTimeEst = rsp.ServerTime + halfRtt;

                    long offset = serverTimeEst - nowLocal;

                    ServerTime.Sync(offset);

                    LogMsg.Info($"RTT = {halfRtt * 2} ms, 时间差={offset} ms");

                    LogMsg.Info($"当前服务器时间：{ServerTime.NowMs}");

                    ((NetClient)serverBase)._pingTimeoutCounter = 0;
                }
            }
        }

        public void OnInit()
        {
        }


    }
}
